package com.excel.controler;

import com.excel.entity.ExcelTable;
import com.excel.poi.ali.AnalysisEventListener;
import com.excel.poi.ali.inter.AnalysisContextImpl;
import com.excel.poi.pojo.ExcelExportVo;
import com.excel.poi.pojo.ExcelImportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 赵玮
 * @Description lb
 * @create /2022/3/14
 */
@RestController
@RequestMapping("ControllerPoi")
public class ControllerPoi {

    @Autowired
    com.excel.poi.util.ExcelUtilSax ExcelUtilSax;
    @Autowired
    com.excel.dao.ExcelTableMapper excelTableMapper;
    @Autowired
    com.excel.poi.util.ExcelUtil ExcelUtil;

    /**
     * sax方式导入
     * @author 赵玮
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/importExcelBySax",method = RequestMethod.POST)
    public   List  importExcelBySax(MultipartFile file) throws Exception {
        List<ExcelTable> objects = new ArrayList<>();
        ExcelUtilSax.readBySax(file.getInputStream(),ExcelTable.class,new AnalysisEventListener<ExcelTable>() {
            @Override
            public void invoke(ExcelTable object, AnalysisContextImpl context) {
                System.out.println(object + "===" + context);
                objects.add(object);
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContextImpl context) {
                System.out.println(context);
            }
        });
        return objects;
    }
    /**
     * 导入 ExcelTable属性为例  50万+
     * @author 赵玮
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public   List  importExcel(MultipartFile file) throws Exception {
        ExcelImportVo excelImportVo = new ExcelImportVo();
        excelImportVo.setHeadRows(1);
        excelImportVo.setPojoClass(ExcelTable.class);
        return ExcelUtil.readExcel(file.getInputStream(),excelImportVo);
    }

    @RequestMapping(value = "/downLoad",method = RequestMethod.POST)
    public  void  downLoad(HttpServletResponse response) throws Exception {
        List<ExcelTable> excelTables = excelTableMapper.selectAll();
        ExcelExportVo excelExportVo = new ExcelExportVo();
        excelExportVo.setFileName("测试");
        excelExportVo.setDataList(excelTables);
        excelExportVo.setSourceClass(ExcelTable.class);
        //报表下载
        ExcelUtil.exportExcel(response,excelExportVo);
    }
}
